package com.excel.qlexpress;



import com.corpgovernment.common.utils.DateUtil;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
public class CommonQlFunction {


    //校验 excel重复数据 动态字段
    public static <T> List<T> getDuplicateOrgField(List<T> list, Function<T, String> fieldMapper){
        Map<String, Long> countMap = list.stream().collect(Collectors.groupingBy(fieldMapper, Collectors.counting()));
        List<T> duplicates = list.stream()
                .filter(e -> countMap.get(fieldMapper.apply(e))>1)
                .collect(Collectors.toList());
        return duplicates;
    }

    public static boolean isValidDate(String dateStr, String formatStr) {
        DateFormat format = new SimpleDateFormat(formatStr);
        format.setLenient(false);
        try {
            format.parse(dateStr);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    public static String buildNewPwd(String phoneNum) {
        if(StringUtils.isBlank(phoneNum)){
            return null;
        }
        String newLast5 = phoneNum.substring(phoneNum.length() - 5);
        // 生成包含字母的随机数
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[4];
        random.nextBytes(bytes);
        String randomStr = Base64.getEncoder().encodeToString(bytes).substring(0, 4);
        return  newLast5 + randomStr;
    }



    public static void main(String[] args) {

        String pwd = "17756097454";
        String aa = Optional.ofNullable(pwd).orElse(CommonQlFunction.buildNewPwd(pwd));

        if(!isValidDate("20-89-09-23",  DateUtil.DF_YMD)) {
            System.out.println("日期格式错误");
        }

    }




}